<template>
  <div class="alarm-page">
    <h1 class="page-title">告警管理</h1>
    
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 告警记录 -->
      <el-tab-pane label="告警记录" name="records">
        <!-- 统计卡片 -->
        <el-row :gutter="20" class="stats-row">
          <el-col :xs="24" :sm="12" :md="6">
            <div class="stat-card total">
              <div class="stat-icon">
                <el-icon :size="32"><Bell /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-label">总告警数</div>
                <div class="stat-value">{{ alarmStats.total }}</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <div class="stat-card unhandled">
              <div class="stat-icon">
                <el-icon :size="32"><Warning /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-label">未处理</div>
                <div class="stat-value">{{ alarmStats.unhandled }}</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <div class="stat-card handled">
              <div class="stat-icon">
                <el-icon :size="32"><CircleCheck /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-label">已处理</div>
                <div class="stat-value">{{ alarmStats.handled }}</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <div class="stat-card rate">
              <div class="stat-icon">
                <el-icon :size="32"><TrendCharts /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-label">处理率</div>
                <div class="stat-value">{{ alarmStats.handleRate }}%</div>
              </div>
            </div>
          </el-col>
        </el-row>
        
        <div class="tab-header">
          <div class="filter-group">
            <el-radio-group v-model="statusFilter" @change="loadAlarms">
              <el-radio-button :label="null">全部</el-radio-button>
              <el-radio-button :label="0">未处理</el-radio-button>
              <el-radio-button :label="1">已处理</el-radio-button>
            </el-radio-group>
            
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              style="margin-left: 10px"
              @change="loadAlarms"
            />
          </div>
          
          <div class="action-group">
            <el-button @click="loadAlarms" :icon="Refresh">刷新</el-button>
            <el-switch
              v-model="autoRefresh"
              active-text="自动刷新"
              style="margin-left: 10px"
            />
          </div>
        </div>
        
        <el-table :data="alarmList" stripe v-loading="loading" style="width: 100%">
          <el-table-column prop="id" label="ID" width="70" align="center" />
          <el-table-column prop="ruleName" label="规则名称" min-width="180" show-overflow-tooltip>
            <template #default="scope">
              <el-tag type="info" effect="plain" size="small">{{ scope.row.ruleName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="logCount" label="触发数量" width="100" align="center">
            <template #default="scope">
              <el-tag type="warning" effect="light" round>
                {{ scope.row.logCount }} 条
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="alarmTime" label="告警时间" width="180" sortable align="center">
            <template #default="scope">
              <div style="font-size: 12px;">{{ formatTime(scope.row.alarmTime) }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="90" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.status === 0 ? 'danger' : 'success'" size="small">
                {{ scope.row.status === 0 ? '未处理' : '已处理' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="handlerName" label="处理人" width="120" align="center">
            <template #default="scope">
              <span v-if="scope.row.handlerName">
                <el-icon style="vertical-align: middle;"><User /></el-icon>
                {{ scope.row.handlerName }}
              </span>
              <span v-else style="color: #909399;">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="handleTime" label="处理时间" width="180" align="center">
            <template #default="scope">
              <div v-if="scope.row.handleTime" style="font-size: 12px;">
                {{ formatTime(scope.row.handleTime) }}
              </div>
              <span v-else style="color: #909399;">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="alarmContent" label="告警内容" show-overflow-tooltip min-width="200" />
          <el-table-column label="操作" width="160" fixed="right" align="center">
            <template #default="scope">
              <el-button
                v-if="scope.row.status === 0"
                type="primary"
                size="small"
                @click="openHandleDialog(scope.row)"
              >
                处理
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="viewAlarmDetail(scope.row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="loadAlarms"
            @current-change="loadAlarms"
          />
        </div>
      </el-tab-pane>
      
      <!-- 告警规则 -->
      <el-tab-pane label="告警规则" name="rules">
        <div class="tab-header">
          <el-button type="primary" @click="openRuleDialog(null)">
            <el-icon><Plus /></el-icon> 新建规则
          </el-button>
        </div>
        
        <el-table :data="ruleList" stripe>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="ruleName" label="规则名称" width="200" />
          <el-table-column prop="description" label="描述" show-overflow-tooltip />
          <el-table-column prop="enabled" label="状态" width="100">
            <template #default="scope">
              <el-switch
                v-model="scope.row.enabled"
                :active-value="1"
                :inactive-value="0"
                @change="toggleRuleStatus(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="openRuleDialog(scope.row)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="deleteRule(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 处理告警对话框 -->
    <el-dialog
      v-model="handleDialogVisible"
      title="处理告警"
      width="500px"
    >
      <el-form :model="handleForm" label-width="80px">
        <el-form-item label="处理备注">
          <el-input
            v-model="handleForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入处理说明"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="handleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitHandle">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 告警详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="告警详情"
      width="700px"
    >
      <el-descriptions :column="2" border v-if="currentAlarm">
        <el-descriptions-item label="告警ID">{{ currentAlarm.id }}</el-descriptions-item>
        <el-descriptions-item label="规则名称">
          <el-tag type="info">{{ currentAlarm.ruleName }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="触发数量">
          <el-tag type="warning">{{ currentAlarm.logCount }} 条</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="告警时间">{{ currentAlarm.alarmTime }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentAlarm.status === 0 ? 'danger' : 'success'">
            {{ currentAlarm.status === 0 ? '未处理' : '已处理' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="处理人">{{ currentAlarm.handlerName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="处理时间" :span="2">{{ currentAlarm.handleTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="告警内容" :span="2">
          <div class="alarm-content-detail">{{ currentAlarm.alarmContent }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="处理备注" :span="2">
          <div class="alarm-remark">{{ currentAlarm.remark || '暂无备注' }}</div>
        </el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button 
          v-if="currentAlarm && currentAlarm.status === 0"
          type="primary" 
          @click="openHandleDialogFromDetail(currentAlarm)"
        >
          立即处理
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 规则对话框 -->
    <el-dialog
      v-model="ruleDialogVisible"
      :title="ruleForm.id ? '编辑规则' : '新建规则'"
      width="600px"
    >
      <el-form :model="ruleForm" label-width="100px">
        <el-form-item label="规则名称">
          <el-input v-model="ruleForm.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="ruleForm.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="触发条件">
          <el-input v-model="ruleForm.condition" type="textarea" :rows="5" placeholder="JSON格式" />
        </el-form-item>
        <el-form-item label="通知邮箱">
          <el-input v-model="ruleForm.notifyEmail" placeholder="多个邮箱用逗号分隔" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="ruleForm.enabled" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="ruleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRule">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onUnmounted, watch } from 'vue'
import { getAlarmList, handleAlarm, getAlarmRules, createAlarmRule, updateAlarmRule, deleteAlarmRule } from '@/api/alarm'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { Bell, Warning, CircleCheck, TrendCharts, Document, Refresh, User } from '@element-plus/icons-vue'

const userStore = useUserStore()
const activeTab = ref('records')
const statusFilter = ref(null)
const dateRange = ref(null)
const alarmList = ref([])
const ruleList = ref([])
const loading = ref(false)
const autoRefresh = ref(false)
let refreshTimer = null

const handleDialogVisible = ref(false)
const ruleDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentAlarm = ref(null)

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const handleForm = reactive({
  alarmId: null,
  remark: ''
})

const ruleForm = reactive({
  id: null,
  ruleName: '',
  description: '',
  condition: '',
  notifyEmail: '',
  enabled: 1
})

// 告警统计
const alarmStats = computed(() => {
  // 确保 alarmList.value 是数组
  const list = Array.isArray(alarmList.value) ? alarmList.value : []
  const total = list.length
  const unhandled = list.filter(a => a.status === 0).length
  const handled = list.filter(a => a.status === 1).length
  const handleRate = total > 0 ? Math.round((handled / total) * 100) : 0
  return { total, unhandled, handled, handleRate }
})

// 加载告警列表
const loadAlarms = async () => {
  loading.value = true
  try {
    const params = { 
      status: statusFilter.value,
      pageNum: pagination.page,
      pageSize: pagination.size
    }
    
    // 如果有时间范围筛选
    if (dateRange.value && dateRange.value.length === 2) {
      params.startTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }
    
    const res = await getAlarmList(params)
    if (res.code === 200) {
      // 处理 MyBatis-Plus Page 对象格式
      if (res.data && Array.isArray(res.data.records)) {
        alarmList.value = res.data.records
        pagination.total = res.data.total || 0
      } else if (Array.isArray(res.data)) {
        // 兼容直接返回数组的情况
        alarmList.value = res.data
        pagination.total = res.total || res.data.length
      } else {
        alarmList.value = []
        pagination.total = 0
      }
    } else {
      alarmList.value = []
      pagination.total = 0
    }
  } catch (error) {
    alarmList.value = []
    pagination.total = 0
    console.error('加载告警失败', error)
  } finally {
    loading.value = false
  }
}

// 加载规则列表
const loadRules = async () => {
  try {
    const res = await getAlarmRules()
    if (res.code === 200) {
      ruleList.value = res.data || []
    } else {
      ruleList.value = []
    }
  } catch (error) {
    ruleList.value = []
    console.error('加载规则失败', error)
  }
}

// 打开处理对话框
const openHandleDialog = (alarm) => {
  handleForm.alarmId = alarm.id
  handleForm.remark = ''
  handleDialogVisible.value = true
}

// 提交处理
const submitHandle = async () => {
  try {
    const res = await handleAlarm({
      alarmId: handleForm.alarmId,
      handlerId: userStore.userId,
      remark: handleForm.remark
    })
    if (res.code === 200) {
      ElMessage.success('处理成功')
      handleDialogVisible.value = false
      loadAlarms()
    }
  } catch (error) {
    ElMessage.error('处理失败')
  }
}

// 打开规则对话框
const openRuleDialog = (rule) => {
  if (rule) {
    Object.assign(ruleForm, rule)
    ruleForm.condition = JSON.stringify(rule.condition, null, 2)
  } else {
    ruleForm.id = null
    ruleForm.ruleName = ''
    ruleForm.description = ''
    ruleForm.condition = ''
    ruleForm.enabled = 1
  }
  ruleDialogVisible.value = true
}

// 提交规则
const submitRule = async () => {
  try {
    const data = {
      ...ruleForm,
      condition: JSON.parse(ruleForm.condition)
    }
    
    const res = ruleForm.id 
      ? await updateAlarmRule(data)
      : await createAlarmRule(data)
      
    if (res.code === 200) {
      ElMessage.success('保存成功')
      ruleDialogVisible.value = false
      loadRules()
    }
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 删除规则
const deleteRule = (rule) => {
  ElMessageBox.confirm('确定删除该规则吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteAlarmRule(rule.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        loadRules()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 查看详情
const viewAlarmDetail = (alarm) => {
  currentAlarm.value = alarm
  detailDialogVisible.value = true
}

// 从详情对话框打开处理对话框
const openHandleDialogFromDetail = (alarm) => {
  detailDialogVisible.value = false
  openHandleDialog(alarm)
}

// 格式化时间显示
const formatTime = (time) => {
  if (!time) return '-'
  // 如果是完整的日期时间格式，提取日期和时间
  if (typeof time === 'string' && time.length > 10) {
    const parts = time.split(' ')
    if (parts.length >= 2) {
      return `${parts[0]}\n${parts[1]}`
    }
  }
  return time
}

// 自动刷新
watch(autoRefresh, (val) => {
  if (val) {
    refreshTimer = setInterval(() => {
      loadAlarms()
    }, 30000) // 30秒刷新一次
    ElMessage.success('已开启自动刷新（每30秒）')
  } else {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
    ElMessage.info('已关闭自动刷新')
  }
})

// 切换规则状态
const toggleRuleStatus = (rule) => {
  updateAlarmRule(rule).then(() => {
    ElMessage.success('状态更新成功')
  })
}

onMounted(() => {
  loadAlarms()
  loadRules()
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
})
</script>

<style scoped lang="scss">
.alarm-page {
  padding: 20px;
  
  .page-title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #303133;
  }
  
  // 统计卡片样式
  .stats-row {
    margin-bottom: 20px;
  }
  
  .stat-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 8px;
    padding: 20px;
    display: flex;
    align-items: center;
    color: white;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    }
    
    &.total {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
    
    &.unhandled {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }
    
    &.handled {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }
    
    &.rate {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
    
    .stat-icon {
      margin-right: 15px;
      opacity: 0.8;
    }
    
    .stat-content {
      flex: 1;
      
      .stat-label {
        font-size: 14px;
        opacity: 0.9;
        margin-bottom: 8px;
      }
      
      .stat-value {
        font-size: 28px;
        font-weight: bold;
      }
    }
  }
  
  .tab-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    
    .filter-group {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 10px;
    }
    
    .action-group {
      display: flex;
      align-items: center;
    }
  }
  
  .count-badge {
    :deep(.el-badge__content) {
      font-weight: bold;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  // 告警详情样式
  .alarm-content-detail {
    padding: 10px;
    background: #f5f7fa;
    border-radius: 4px;
    white-space: pre-wrap;
    word-break: break-all;
    max-height: 200px;
    overflow-y: auto;
  }
  
  .alarm-remark {
    padding: 10px;
    background: #f0f9ff;
    border-radius: 4px;
    color: #606266;
  }
  
  // 响应式设计
  @media (max-width: 768px) {
    padding: 10px;
    
    .page-title {
      font-size: 20px;
    }
    
    .stat-card {
      padding: 15px;
      margin-bottom: 10px;
      
      .stat-content .stat-value {
        font-size: 24px;
      }
    }
    
    .tab-header {
      flex-direction: column;
      align-items: stretch;
      
      .filter-group,
      .action-group {
        width: 100%;
        justify-content: space-between;
      }
    }
  }
}
</style>

